<script setup>
  import { ref } from "vue";
  import interviewApi from '@/api/interview/index.js';
  import ResponseUtil from "@/utils/ResponseUtil.js";
  import {ElMessage} from "element-plus";

  let contentType = ref('null');
  let fileName = ref();
  let uploadId = ref('');
  let total = ref(0);
  let index = ref(0);
  let result = ref('stop');
  let url = ref('');

  let loading = ref(false);

  let file = null;

  const change = (event) => {
    file = event.target.files[0];

    contentType.value = event.target.files[0].type;
    fileName.value = event.target.files[0].name;
  }

  const upload = async () => {
    if (loading.value) {
      ElMessage.warning('文件正在上传，请勿重复操作！')
      return;
    }
    loading.value = true;

    uploadId.value = '';
    url.value = '';
    index.value = 0;

    result.value = 'wait';
    // 计算当前文件安装一定的大小（12MB）拆分的切片数量
    const total_slice = Math.ceil(file.size / (1024 * 1024 * 6));

    total.value = total_slice;

    // 切片的起始位置和结束位置
    let slice_start = 0;
    let slice_end = Math.min(file.size, 1024 * 1024 * 6);

    // 开始循环进行文件分片
    for (let i = 0; i < total_slice; i++) {
      index.value = i + 1;
      // 切片方法 slice(start, end)
      const slice = file.slice(slice_start, slice_end);

      // 创建表单参数对象
      let data = new FormData();
      data.append("file", slice);
      data.append("index", i);
      data.append("fileName", fileName.value);
      data.append("totalChunks", total_slice);
      data.append("contentType", contentType.value);
      data.append("uploadId", uploadId.value);

      // 将本次的切片上传到服务器中
      let response = await interviewApi.uploadMaxFile(data);
      uploadId.value = response.data.uploadId;

      // 更新切片的起始位置和结束位置
      slice_start = slice_end;
      slice_end = Math.min(slice_start + 1024 * 1024 * 6, file.size);
    }

    // 请求服务器合并文件分片
    const req = {
      fileName: fileName.value,
      uploadId: uploadId.value
    }
    interviewApi.mergeMaxFile(req).then(response => {
      ResponseUtil.data(response).dispose(response => {
        url.value = response.data.url;
      })
    })

    result.value = 'success';
    loading.value = true;
  }

</script>

<template>
  <div class="basic">
    <div>上传文件名称：{{ fileName }}</div>
    <div>上传文件类型：{{ contentType }}</div>
    <div>文件总分片数：{{ total }}</div>
    <div>当上传分片数：{{ index }}</div>
    <div>文件上传结构：{{ result }}</div>
    <div>文件访问地址：{{ url }}</div>
    <br>
    <input type="file" @change="change($event)">
    <br>
    <br>
    <el-button type="primary" @click="upload">上传文件</el-button>
  </div>
</template>

<style scoped>
  .basic {
    width: 600px;
    height: 500px;
    position: absolute;
    top: calc(50% - 250px);
    left: calc(50% - 300px);
    border: 1px solid rgb(102, 102, 102);
  }
</style>